package com.framework.foundation.system.dictionary;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import com.framework.foundation.common.BaseService;
import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class DictionaryDetailService extends BaseService<DictionaryDetail> {

	public static final DictionaryDetailService me = Enhancer.enhance(DictionaryDetailService.class);

	/**
	 * 根据数据分类目录获取数据字典集合(easyui-treegrid格式)
	 * 
	 * @param
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月3日 下午5:42:12
	 */
	public List<Record> treeGridJson(Map<String, Object> param) {
		int dictionaryId = MapUtils.getIntValue(param, "dictionaryId", 0);
		List<Record> list = Db.find(
				"SELECT id, code, name, enabled FROM ww_dictionary_detail WHERE deleteMark = 0 AND dictionaryId = ? AND parentId = 0 ORDER BY sort, id",
				dictionaryId);
		if (CollectionUtils.isNotEmpty(list)) {
			for (Record dd : list) {
				List<Record> children = getChildren(dd.getInt("id"));
				if (CollectionUtils.isNotEmpty(children)) {
					dd.set("children", children);
				} else {
					dd.set("state", "open");
				}
			}
		}
		return list;
	}

	/**
	 * 递归获取子节点
	 * 
	 * @param parentId
	 * @return
	 * @Author: Brin
	 * @Date: 2015年12月22日 上午11:19:57
	 */
	public List<Record> getChildren(int parentId) {
		List<Record> children = Db.find(
				"SELECT id, code, name, enabled FROM ww_dictionary_detail WHERE deleteMark = 0 AND parentId = ? ORDER BY sort, id",
				parentId);
		if (CollectionUtils.isNotEmpty(children)) {
			// 递归获取子节点信息
			for (Record dd : children) {
				List<Record> cd = getChildren(dd.getInt("id"));
				if (CollectionUtils.isNotEmpty(cd)) {
					dd.set("children", cd);
				}
			}
		}
		return children;
	}

	/**
	 * 根据参数获取数据字典树形json
	 * 
	 * @param
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月3日 下午5:42:12
	 */
	public List<Record> treeJson(Map<String, Object> param) {
		int dictionaryId = MapUtils.getIntValue(param, "dictionaryId");
		int id = MapUtils.getIntValue(param, "id", 0);

		StringBuffer sql = new StringBuffer(
				"SELECT id, parentId, name FROM ww_dictionary_detail WHERE deleteMark = 0 AND dictionaryId = "
						+ dictionaryId);
		// 如果为编辑状态下则需要排除上级选择自己和自己子节点的可能
		if (id != 0) {
			sql.append(" AND id <> " + id);
		}

		return Db.find(sql.toString());
	}

}
